package com.mdjukebox.services.quartz.jobs;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.ResourceBundle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.mdjukebox.model.jukeboxfacade.actions.AltaPeticionAction;
import com.mdjukebox.model.vo.PeticionVO;
import com.opensms.mo.MOFacade;
import com.opensms.mo.MOFactory;
import com.opensms.mo.SMSVO;
import com.opensms.mt.MTFacade;
import com.opensms.mt.MTFactory;
import com.util.sql.PlainActionProcessor;

public class JobRecepcionPeticionesMail implements Job {

	public static final Log log = LogFactory.getLog(JobRecepcionPeticionesMail.class);
	
	public void execute(JobExecutionContext context) throws JobExecutionException 
	{
		if (log.isDebugEnabled()) {
			log.debug("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nEjecutando recepcion de buzon\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
		}
		try 
		{
			ResourceBundle resources = ResourceBundle.getBundle("com.mdjukebox.http.view.messages.JukeboxMessages");

			MOFacade mo = MOFactory.get();
			MTFacade mt = MTFactory.get();
			Iterator it = mo.getRecentSMSs().iterator();
			SMStoPeticion trans = SMStoPeticion.getInstance();
			
			int i = 0;
			while (it.hasNext()){
				i++;
				//si un mensaje falla seguir con los siguientes
				try{
					SMSVO sms = (SMSVO) it.next();	
					if (log.isDebugEnabled()) log.debug("Pedido: " + sms.toString());
	
					//registrar peticion por sms
					PeticionVO pet = trans.toPeticion(sms);
					if (log.isDebugEnabled()) log.debug("peticion "+ pet.toString());
					
					AltaPeticionAction action = new AltaPeticionAction(pet);
					HashMap rdo = (HashMap) PlainActionProcessor.process(action);
	
					//responder al SMS
					Object[] argumentos = {rdo.get("falta")};
					String msg = MessageFormat.format(resources.getString("RdoPeticion.Confirm"),argumentos);
					if (log.isDebugEnabled()) log.debug("Respondido: " + msg);
					mt.enviarSMS(sms.getMovil(), msg);
				}catch (Exception e){
					if (log.isErrorEnabled()) log.error("While Job: ",e);
				}
			}
			if (log.isDebugEnabled()) log.debug("Se han tratado " + i +"  SMS ");	
		} 
		catch (Exception e)
		{
			if (log.isErrorEnabled()) log.error("Job: ",e);
		}
		if (log.isDebugEnabled()){
	   		log.debug("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nFin de la ejecucion recepcion de buzon\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
		}
	}

}